//
//  FastOrder.m
//  VivaModa
//
//  Created by Sergey on 3/27/13.
//  Copyright (c) 2013 private_busines. All rights reserved.
//

#import "FastOrder.h"
#import "fast_order_cell.h"

@interface FastOrder (){
    UITextField *test_textField;
    NSArray *array_step_reg;
}
@property (strong, nonatomic) NSArray *dataLocation;
@property (strong, nonatomic) NSMutableArray *sortedArrayRegion;
@property (strong, nonatomic) NSMutableArray *sortedArrayCountry;

@property (strong, nonatomic) NSMutableArray *arrayDelivery;
@end

@implementation FastOrder
@synthesize tableView;
@synthesize email;
@synthesize button_send_order;
@synthesize connection_sendOrder;
@synthesize sendOrderData;
@synthesize connection_locate;
@synthesize locateData;
@synthesize pickerView;

@synthesize dataLocation;
@synthesize sortedArrayRegion;
@synthesize sortedArrayCountry;
@synthesize arrayDelivery;


@synthesize strana;
@synthesize region;
@synthesize delivery;
@synthesize type_payments;

@synthesize strana_label;
@synthesize region_label;
@synthesize delivery_label;
@synthesize type_payments_label;

@synthesize adress;

NSString *text_name1;
NSString *text_telephone1;

NSString *last_text_type_payment_;
NSString *last_text_type_payment_db_;

NSString *text_type_payment_;/// text for payment
NSString *text_type_payment_db_;/// text for payment

int current_id_countryes = -1;
int last_countryes_id = 0;/// что б небыло в Украине Москвы
int last_zones_id = 0;///
int id_tapped_button ;

bool showed_pickers;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    sortedArrayRegion = [[NSMutableArray alloc] initWithCapacity:1];
    sortedArrayCountry = [[NSMutableArray alloc] initWithCapacity:1];
    arrayDelivery = [[NSMutableArray alloc] initWithCapacity:1];
    
    [self getLocationData];
    [self hidePicker:NO];
    
    array_step_reg = @[@"Имя (обязательно *)",@"Телефон (обязательно *)"];
    
    [self setNavigationTitle];
    [self addCustomBackButton];
    
    [self.button_send_order setBackgroundImage:[UIImage imageNamed:@"bg_catalog_cell"] forState:UIControlStateNormal];
    
    [self.button_send_order setContentEdgeInsets:UIEdgeInsetsMake(0, 0, 4, 0)];
    // Do any additional setup after loading the view from its nib.
    [self setRequiredStars];
}



-(void)setRequiredStars{
    NSString* name_step1 = @"Страна (обязательно *)";
    NSRange range = [name_step1 rangeOfString:@"*"];
    NSMutableAttributedString* attrStr1 = [NSMutableAttributedString attributedStringWithString:name_step1];
    [attrStr1 setFont:[UIFont systemFontOfSize:14]];
    [attrStr1 setTextColor:[UIColor blackColor]];
    [attrStr1 setTextColor:[UIColor redColor] range:range];
    strana_label.attributedText = attrStr1;
    
    
    NSString* name_step2 = @"Регион (обязательно *)";
    NSRange range2 = [name_step2 rangeOfString:@"*"];
    NSMutableAttributedString* attrStr2 = [NSMutableAttributedString attributedStringWithString:name_step2];
    [attrStr2 setFont:[UIFont systemFontOfSize:14]];
    [attrStr2 setTextColor:[UIColor blackColor]];
    [attrStr2 setTextColor:[UIColor redColor] range:range2];
    region_label.attributedText = attrStr2;
    
    
    NSString* name_step3 = @"Способ доставки (обязательно *)";
    NSRange range3 = [name_step3 rangeOfString:@"*"];
    NSMutableAttributedString* attrStr3 = [NSMutableAttributedString attributedStringWithString:name_step3];
    [attrStr3 setFont:[UIFont systemFontOfSize:14]];
    [attrStr3 setTextColor:[UIColor blackColor]];
    [attrStr3 setTextColor:[UIColor redColor] range:range3];
    delivery_label.attributedText = attrStr3;
    
    
    NSString* name_step4 = @"Способ оплаты (обязательно *)";
    NSRange range4 = [name_step4 rangeOfString:@"*"];
    NSMutableAttributedString* attrStr4 = [NSMutableAttributedString attributedStringWithString:name_step4];
    [attrStr4 setFont:[UIFont systemFontOfSize:14]];
    [attrStr4 setTextColor:[UIColor blackColor]];
    [attrStr4 setTextColor:[UIColor redColor] range:range4];
    type_payments_label.attributedText = attrStr4;
}





- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"fast_order_cell";
    
    
    
    fast_order_cell *cell = nil;
    cell = (fast_order_cell *) [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell)
    {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"fast_order_cell" owner:nil options:nil];
        for(id currentObject in topLevelObjects)
        {
            if([currentObject isKindOfClass:[fast_order_cell class]])
            {
                cell = (fast_order_cell *)currentObject;
                break;
            }
        }
    }
    
    
    if (indexPath.row==0) {
        cell.text_field.text = text_name1;
        cell.text_field.tag = 1;
    }else{
        cell.text_field.text = text_telephone1;
        cell.text_field.tag = 2;
    }
    
    cell.text_field.delegate = self;
    
    
    
    NSString* name_step = [array_step_reg objectAtIndex:indexPath.row];
    NSRange range = [name_step rangeOfString:@"*"];
    NSMutableAttributedString* attrStr2 = [NSMutableAttributedString attributedStringWithString:name_step];
    [attrStr2 setFont:[UIFont systemFontOfSize:14]];
    [attrStr2 setTextColor:[UIColor blackColor]];
    [attrStr2 setTextColor:[UIColor redColor] range:range];
    cell.name_steps.attributedText = attrStr2;
    
    
    
    
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UIView *bg_sel = [[UIView alloc] initWithFrame:cell.bounds];
    bg_sel.backgroundColor = [UIColor clearColor];
    cell.selectedBackgroundView = bg_sel;
    
    
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 65;
}



- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    int id_cell = textField.tag;
    
    NSString *text;
    if (range.length<1) {
        
        text = [NSString stringWithFormat:@"%@%@",textField.text,string];
    }else{
        text = [textField.text substringToIndex:[textField.text length] - 1];
    }
    
    
    switch (id_cell) {
        case 1:{
            text_name1 = text;
            break;}
        case 2:{
            text_telephone1 = text;
            break;}
               default:
            break;
    }
    
    return YES;
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [textField resignFirstResponder];
    return YES;
}


-(void) textFieldDidBeginEditing:(UITextField *)textField {
    
    if (showed_pickers) {
        [self hidePicker:YES];
    }
    
    
    test_textField = textField;
    CGPoint pnt;
    NSIndexPath* path;
    if (textField.tag ==3) {
        [self.tableView setContentOffset:CGPointMake(0, tableView.contentSize.height-320) animated:YES];
        
    }else{
        if (textField.tag ==4) {
            [self.tableView setContentOffset:CGPointMake(0, tableView.contentSize.height-520) animated:YES];
            
        }else{
            pnt = [self.tableView convertPoint:textField.bounds.origin fromView:textField];
            path = [self.tableView indexPathForRowAtPoint:pnt];
            [self performSelector:@selector(aaaap:) withObject:path afterDelay:0.1];
        }
    }
    
    

}

-(void)aaaap:(NSIndexPath*)path{
    [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionTop animated:YES];
}




#pragma mark Dejal activity

- (void)displayActivityView
{
    //[self removeActivityView];
    
    if ([DejalActivityView isActive]) {
        return;
    }
    
    UIView *viewToUse = self.tabBarController.tabBar.superview;
    [DejalBezelActivityView activityViewForView:viewToUse];
    [DejalActivityView currentActivityView].showNetworkActivityIndicator = YES;
    [DejalActivityView currentActivityView].activityLabel.text = @"Синхронизация";
    //[self performSelector:@selector(removeActivityView) withObject:nil afterDelay:3.0];
}

- (void)removeActivityView;
{
    [DejalBezelActivityView removeViewAnimated:YES];
    [[self class] cancelPreviousPerformRequestsWithTarget:self];
}

#pragma mark



-(void)getLocationData{
    
    NSURL* url = [NSURL URLWithString:@"http://moda.viva-viva.ru/mobile/get_location.php"]; // куда отправлять
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    connection_locate = [NSURLConnection connectionWithRequest:request delegate:self];
    [self displayActivityView];
    if (connection_locate) {
        self.locateData = [NSMutableData data];
    }
}




























- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    //[self removeActivityView];
    [self showNoInternetAlert];
}



- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if (connection == connection_sendOrder) {
        [sendOrderData appendData:data];
    }else{
        if (connection == connection_locate) {
            [locateData appendData:data];
        }
    }
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    if (connection == connection_sendOrder) {
        [self parseJSON:sendOrderData type:1];
    }else{
        if (connection == connection_locate) {
            [self parseJSON:locateData type:2];
        }
    }
}


#pragma mark parse JSON result

-(void)parseJSON:(NSData*)data type:(int)type{ /// 1 - send order 2 - location
    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                          JSONObjectWithData:data
                          options:kNilOptions
                          error:&error];
    
    NSString* requestResultAutorization = [json objectForKey:@"success"];
    
    
    
    NSLog(@"%@",json);
    
    if ([requestResultAutorization integerValue]==1) {
        if (type==1) {
            BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:[json objectForKey:@"message"]];
            [alert setCancelButtonWithTitle:@"Закрыть" block:^{
                [self removeActivityView];
            }];
            [alert show];
            [SQLiteAccess deleteWithSQL:@"DELETE FROM Basket"];
            [[Singleton sharedMySingleton] setBadge];
        }else{
            if (type==2) {
                NSArray * array_location = [json objectForKey:@"message"];
                if ([array_location count]>0) {
                    dataLocation = array_location;
                    [self sortCountryFromArray:array_location];;
                }else{
                    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Уведомление" message:@"Ошибка синхронизации с сервером"];
                    [alert setCancelButtonWithTitle:@"Закрыть" block:^{
                    }];
                    [alert show];
                }
            }
        }
        
        


    }else{
        BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Ошибка" message:[json objectForKey:@"message"]];
        [alert setCancelButtonWithTitle:@"Закрыть" block:^{
            [self removeActivityView];
        }];
        [alert show];
    }
    
    
    [self removeActivityView];
}



-(void)sortCountryFromArray:(NSArray*)array_data{
    if ([array_data count]>0) {
        [sortedArrayRegion removeAllObjects];
        NSSet * set = [NSSet setWithArray:[array_data valueForKey:@"country_id"]];
        NSMutableArray *sorted_array = [[set allObjects] mutableCopy];
        
        for (int j =0; j<[sorted_array count]; j++) {
            for (int i =0; i < [array_data count]; i++) {
                if ([[[array_data objectAtIndex:i] objectForKey:@"country_id"] integerValue]==[[sorted_array objectAtIndex:j]  integerValue]) {
                    NSString *id_country = [[array_data objectAtIndex:i] objectForKey:@"country_id"];
                    NSString *name_country = [[array_data objectAtIndex:i] objectForKey:@"country_name"];
                    NSString *id_zone = [[dataLocation objectAtIndex:i] objectForKey:@"zone_id"];
                    NSDictionary *dict = @{@"country_id" : id_country, @"country_name" : name_country,@"zone_id" : id_zone};
                    [sortedArrayCountry addObject:dict];
                    break;
                }
            }
        }
        
        if ([sortedArrayCountry count]>0) {
            current_id_countryes = [[[sortedArrayCountry objectAtIndex:0] objectForKey:@"country_id"] integerValue];
            [self sortRegionWithIdCountry:current_id_countryes];
        }
        
        //NSLog(@"sortedArrayCountry  = %@",sortedArrayCountry);
        
    }
}


-(void)sortRegionWithIdCountry:(int)id_country{
    [sortedArrayRegion removeAllObjects];
    
    NSDictionary *dict_clear = @{@"country_id" : @"0", @"name_zone":@"",@"zone_id":@"0"};
    [sortedArrayRegion addObject:dict_clear];
    
    for (int i =0; i < [dataLocation count]; i++) {
        if ([[[dataLocation objectAtIndex:i] objectForKey:@"country_id"] integerValue]==id_country) {
            NSString *id_country = [[dataLocation objectAtIndex:i] objectForKey:@"country_id"];
            NSString *name_zone = [[dataLocation objectAtIndex:i] objectForKey:@"name_zone"];
            NSString *id_zone = [[dataLocation objectAtIndex:i] objectForKey:@"zone_id"];
            NSDictionary *dict = @{@"country_id" : id_country, @"name_zone" : name_zone,@"zone_id" : id_zone};
            [sortedArrayRegion addObject:dict];
        }
    }
    last_countryes_id = id_country;
    //NSLog(@"sortedArrayRegion = %@",sortedArrayRegion);
}




-(void)updateDeliveryChoose{
    [arrayDelivery removeAllObjects];
    
    if (last_countryes_id==176) {
        /////// Россия
        
        if (last_zones_id == 98) {// Москва
            [arrayDelivery addObject:@"Бесплатная доставка"];
            [arrayDelivery addObject:@"Самовывоз"];
            [arrayDelivery addObject:@"Курьерская доставка"];
        }else{
            [arrayDelivery addObject:@""];
            [arrayDelivery addObject:@"EMS Почта России 3-6 дней"];
        }
    }else{
        /////// Остальные страны
        [arrayDelivery addObject:@""];
        [arrayDelivery addObject:@"EMS Почта России (международное отправление)"];
    }
}










- (IBAction)openAlertPicker:(id)sender {
    
    last_text_type_payment_ = [Singleton sharedMySingleton].text_payment;
    last_text_type_payment_db_ = [Singleton sharedMySingleton].text_payment_db;
    
    
	PickerAlertView *pickerAlertView = [[PickerAlertView alloc] initWithTitle:@" " message:@" " delegate:self cancelButtonTitle:@"Отмена" otherButtonTitles:@"Выбрать", nil];
    
    //[pickerAlertView setBackgroundColor:[UIColor redColor]];
    
    pickerAlertView.tag = 111;
	[pickerAlertView show];
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(PickerAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (alertView.tag == 111) {
        if (buttonIndex == 0) {
            NSLog(@"cencel");
            text_type_payment_ = last_text_type_payment_;
            text_type_payment_db_ = last_text_type_payment_db_;
        }else{
            text_type_payment_ = [Singleton sharedMySingleton].text_payment;
            text_type_payment_db_ = [Singleton sharedMySingleton].text_payment_db;
            NSLog(@"Good");
            self.type_payments.text = text_type_payment_;
        }
        
    }
    
}








- (void)showNoInternetAlert
{
    BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Ошибка Internet соединения" message:@"Для работы с магазином необходимо подключение к сети Internet. Пожалуйста, проверте подключение к сети и повторите попытку."];
    [alert setCancelButtonWithTitle:@"Закрыть" block:^{
        [UserDefaults setObject:@"NO" forKey:@"SuccsesUpdateCategories"];
        [self removeActivityView];
    }];
    //[alert setDestructiveButtonWithTitle:@"Повторить" block:nil];
    [alert addButtonWithTitle:@"Повторить " block:^{
        //[self displayActivityView];
        [self performSelector:@selector(parseCategories) withObject:nil afterDelay:1.0];
        //[self parseCategories];
    }];
    [alert show];
}


-(BOOL)InternetConnection{
    internetReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [internetReach currentReachabilityStatus];
    if (netStatus == ReachableViaWiFi || netStatus == ReachableViaWWAN) {
        return YES;
    }else{
        return NO;
    }
    
}



#pragma mark - picker Methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)thePickerView
numberOfRowsInComponent:(NSInteger)component
{
    if (id_tapped_button==3) {
        return sortedArrayCountry.count;
    }else{
        if (id_tapped_button==4) {
            return sortedArrayRegion.count;
        }else{
            if (id_tapped_button==5) {
                return arrayDelivery.count;
            }else{
                return 0;
            }
            
        }
    }
    
}

- (NSString *)pickerView:(UIPickerView *)thePickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component
{
    if (id_tapped_button==3) {
        return [[sortedArrayCountry objectAtIndex:row] objectForKey:@"country_name"];
    }else{
        if (id_tapped_button==4) {
            return [[sortedArrayRegion objectAtIndex:row] objectForKey:@"name_zone"];
        }else{
            if (id_tapped_button==5) {
                return [arrayDelivery objectAtIndex:row];
            }else
            return @"";
        }
        
    }
}



-(IBAction)touchOpenPicker:(id)sender{
    [test_textField resignFirstResponder];
    id_tapped_button = [sender tag];
    [self openPicker:self];
    
    [pickerView reloadAllComponents];
    
}

- (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (id_tapped_button==3) {
        strana.text = [[sortedArrayCountry objectAtIndex:row] objectForKey:@"country_name"];
        
        current_id_countryes = [[[sortedArrayCountry objectAtIndex:row] objectForKey:@"country_id"] integerValue];
        
           
        if (last_countryes_id!=current_id_countryes) {
            region.text= @"";
            
        }
        
        [self sortRegionWithIdCountry:current_id_countryes];
        
        [self updateDeliveryChoose];
        
    }else{
        if (id_tapped_button==4) {
            last_zones_id = [[[sortedArrayRegion objectAtIndex:row] objectForKey:@"zone_id"] integerValue];
            region.text = [[sortedArrayRegion objectAtIndex:row] objectForKey:@"name_zone"];
            [self updateDeliveryChoose];
        }else{
            if (id_tapped_button==5) {
                delivery.text = [arrayDelivery objectAtIndex:row];
            }
        }
        
                
    }

    
}


-(IBAction)openPicker:(id)sender{
    bool need_show_picker = NO;
    if (id_tapped_button==3 || id_tapped_button==4) {
        if ([sortedArrayCountry count]>0 && [sortedArrayRegion count]>0) {
            [self hidePicker:NO];
            showed_pickers = YES;
            need_show_picker = YES;
         }
    }else{
        if (id_tapped_button==5) {
            if ([arrayDelivery count]>0) {
                [self hidePicker:NO];
                showed_pickers = YES;
                
                need_show_picker = YES;
            }
        }
    }
    
    if (need_show_picker) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5f];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        pickerView.center = CGPointMake(pickerView.frame.size.width/2, self.view.frame.size.height - pickerView.frame.size.height/2);
        [UIView commitAnimations];
    }
    
    
    
}


-(void)hidePicker:(BOOL)animate{
    showed_pickers = NO;
    if (animate) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5f];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
        pickerView.center = CGPointMake(pickerView.frame.size.width/2, [UIScreen mainScreen].bounds.size.height+pickerView.frame.size.height);
        [UIView commitAnimations];
    }else{
        pickerView.center = CGPointMake(pickerView.frame.size.width/2, [UIScreen mainScreen].bounds.size.height+pickerView.frame.size.height);
    }
}


-(void)upScrolFromPicker:(NSIndexPath*)path{
    [self.tableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionTop animated:YES];
}


#pragma mark -

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (showed_pickers) {
        [self hidePicker:YES];
    }
    [test_textField resignFirstResponder];
}







-(void)setNavigationTitle{
    UILabel *lblTitle = [[UILabel alloc] init];
    lblTitle.text = @"Оформление заказа";
    lblTitle.backgroundColor = [UIColor clearColor];
    lblTitle.textColor = [UIColor colorWithRed:242.0/255.0 green:240.0/255.0 blue:234.0/255.0 alpha:1];
    
    lblTitle.font = [UIFont fontWithName:@"American Retro" size:27.0];
    [lblTitle sizeToFit];
    
    self.navigationItem.titleView = lblTitle;
}

-(void)addCustomBackButton{
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 71, 29)];
      
    [backButton setBackgroundImage:[[UIImage imageNamed:@"img_back_btn.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(8, 20, 20, 20) ] forState:UIControlStateNormal];
    
    [backButton setTitle:@" Корзина" forState:UIControlStateNormal];
    [backButton.titleLabel setFont:[UIFont fontWithName:@"Arial-BoldMT" size:12]];
    
    [backButton setShowsTouchWhenHighlighted:NO];
    [backButton addTarget:self action:@selector(popViewControllerWithAnimation) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barBackItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.hidesBackButton = TRUE;
    self.navigationItem.leftBarButtonItem = barBackItem;
}




-(void)popViewControllerWithAnimation{
    [self.navigationController popViewControllerAnimated:YES];
}



-(IBAction)sendOrder:(id)sender{
    NSArray *array_orders = [SQLiteAccess selectManyRowsWithSQL:@"SELECT id_product, count FROM Basket"];
    if ([text_name1 length]>2 && [text_telephone1 length]>5 && last_zones_id>0 && last_countryes_id>0 && [type_payments.text length]>2 && [delivery.text length]>2 && [strana.text length]>2 && [region.text length]>2) {
         NSString *orders = @"";
        
        for (int i = 0; i<[array_orders count]; i++) {
            orders = [NSString  stringWithFormat:@"%@%@:%@;",orders,[[array_orders objectAtIndex:i] objectForKey:@"id_product"],[[array_orders objectAtIndex:i] objectForKey:@"count"]];
        }
        
        
        
        
        
      NSString *params = [NSString stringWithFormat:@"customer_id=-1&order=%@&user_name=%@&user_tel=%@&zones_id=%i&countryes_id=%i&payment_method=%@&delivery=%@&address=%@",orders,text_name1,text_telephone1,last_zones_id,last_countryes_id,text_type_payment_db_,delivery.text,adress.text];
        
        
        NSLog(@"params=%@",params);
        
        
        NSURL* url = [NSURL URLWithString:@"http://moda.viva-viva.ru/mobile/add_order.php"]; // куда отправлять
        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
        request.HTTPMethod = @"POST";
        request.HTTPBody = [params dataUsingEncoding:NSUTF8StringEncoding]; // следует обратить внимание на кодировку
        
        connection_sendOrder = [NSURLConnection connectionWithRequest:request delegate:self];
        [self displayActivityView];
        
        if (connection_sendOrder) {
            self.sendOrderData = [NSMutableData data];
        }
        
    }else{
        BlockAlertView *alert = [BlockAlertView alertWithTitle:@"Ошибка ввода" message:@"Для оформления заказа необходимо корректно заполнить все обязательные поля(*)"];
        [alert setCancelButtonWithTitle:@"Закрыть" block:^{
            
        }];
        [alert show];
    }
}



@end
